<template>
  <template v-for="menu in menuTree" :key="menu.id">
    <el-sub-menu v-if="menu.hasChildren" :index="menu.id">
      <template #title>
        <el-icon v-if="menu.attributes.icon != ''">
          <component :is="menu.attributes.icon" />
        </el-icon>
        <span>{{ menu.text }}</span>
      </template>
      <el-menu-item
        v-for="chmenu in menu.children"
        :key="chmenu.id"
        :index="'/' + chmenu.attributes.url"
        @click="handleTabAdd(chmenu)"
      >
        <el-icon v-if="chmenu.attributes.icon != ''">
          <component :is="chmenu.attributes.icon" />
        </el-icon>
        <span>{{ chmenu.text }}</span>
      </el-menu-item>
    </el-sub-menu>
    <el-menu-item v-else :index="'/' + menu.attributes.url" @click="handleTabAdd(menu)">
      <el-icon v-if="menu.attributes.icon != ''">
        <component :is="menu.attributes.icon" />
      </el-icon>
      <span>{{ menu.text }}</span>
    </el-menu-item>
  </template>
</template>

<script>
import { onMounted, reactive, toRefs } from 'vue'
import { useMutitabsStore } from '@/stores/mutitabs.js'

export default {
  setup() {
    const state = reactive({
      menuTree: [],
    })
    onMounted(() => {
      getMenu()
    })
    const store = useMutitabsStore()
    // 加载菜单方法
    const getMenu = () => {
      state.menuTree = JSON.parse(localStorage.getItem('menuTree'))
    }

    // 数组去重
    const uniqueArray = (arr, uniId) => {
      const res = new Map()
      return arr.filter((item) => !res.has(item[uniId]) && res.set(item[uniId], 1))
    }

    // 菜单点击事件
    const handleTabAdd = (obj) => {
      // 1.取出已经打开的Tab数组
      const openTabsNew = store.openTabs
      // 2.当前待添加的项
      let tab = { title: obj.text, name: obj.attributes.url }
      // 3.添加到数组
      openTabsNew.push(tab)
      // 4.修改状态管理
      store.$patch({
        activeName: obj.attributes.url,
        openTabs: uniqueArray(openTabsNew, 'name'),
      })
    }
    return {
      handleTabAdd,
      ...toRefs(state),
    }
  },
}
</script>

<style lang="scss" scoped></style>
